package com.leyou.item.web;

import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.service.CategoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("/category")
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    /**
     * 根据id查询商品分类
     * @param id 分类id
     * @return 分类对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<CategoryDTO> queryCategoryById(@PathVariable("id") Long id){
        // 根据id查询对象
        // Category category = categoryService.getById(id);
        // 对象转为DTO
        // CategoryDTO categoryDTO = new CategoryDTO(category);
        // 返回200
        // return ResponseEntity.ok(categoryDTO);

        return ResponseEntity.ok(new CategoryDTO(categoryService.getById(id)));
    }

    /**
     * 根据id集合查询商品分类集合
     * @param ids id集合
     * @return 分类集合
     */
    @GetMapping("list")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByIds(@RequestParam("ids") List<Long> ids){
        // 根据id批量查询分类
        List<Category> list = categoryService.listByIds(ids);
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
        // return ResponseEntity.ok(CategoryDTO.convertEntityList(categoryService.listByIds(ids)));
    }

    /**
     * 根据父类目id查询子类目的集合
     * @param id 父的id
     * @return 类目集合
     */
    @GetMapping("/of/parent")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByPid(@RequestParam("pid") Long id){
        // WHERE parent_id = 0
        List<Category> list = categoryService.query().eq("parent_id", id).list();
        // 转换DTO
        List<CategoryDTO> dtoList = CategoryDTO.convertEntityList(list);
        // 返回
        return ResponseEntity.ok(dtoList);
    }

    /**
     * 根据品牌id查询分类集合
     * @param brandId 品牌id
     * @return 分类集合
     */
    @GetMapping("/of/brand")
    public ResponseEntity<List<CategoryDTO>> queryCategoryByBrandId(@RequestParam("id") Long brandId){
        return ResponseEntity.ok(categoryService.queryCategoryByBrandId(brandId));
    }
}
